package easy.trace.plugin.springmvc.utils;

import easy.trace.core.common.Constants;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author easy
 */
public class RequestHelper {

    public static boolean containsTraceHeader(HttpServletRequest request) {
        if (Objects.isNull(request)) {
            return false;
        }
        Enumeration<String> headerNames = request.getHeaderNames();
        Set<String> headerSet = new HashSet<>();
        while (headerNames.hasMoreElements()) {
            headerSet.add(headerNames.nextElement());
        }
        if (!headerSet.contains(Constants.TRACE_ID.toLowerCase())) {
            return false;
        }
        if (!headerSet.contains(Constants.PARENT_ID.toLowerCase())) {
            return false;
        }
        if (!headerSet.contains(Constants.SPAN_ID.toLowerCase())) {
            return false;
        }
        return true;
    }


    public static String replaceURL(HttpServletRequest request) {
        String dstPath;
        try {
            dstPath = new URL(request.getRequestURL().toString()).getPath();
        } catch (Exception e) {
            dstPath = request.getRequestURI();
        }
        if (dstPath == null || isHealthCheck(dstPath)) {
            return null;
        }
        try {
            dstPath = dstPath.replace("/", ".");
            if (dstPath.startsWith(".")) {
                dstPath = dstPath.substring(1, dstPath.length());
            }
            if (dstPath.endsWith(".")) {
                dstPath = dstPath.substring(0, dstPath.length() - 1);
            }
        } catch (Throwable e) {
            return dstPath.replace("/", ".");
        }
        return dstPath;
    }

    private static boolean isHealthCheck(String path) {
        if (path.contains("yhops") ||
                path.contains("catalog.services") ||
                path.contains("agent.self")) {
            return true;
        }
        return false;
    }

}
